package Copy;

import CodeConvert.EncodingDetect;

import java.io.*;

public class CopyAndCodeConvert {
    public static void main(String[] args) throws IOException {
        copy("C:\\Users\\z\\Desktop","E:\\");
        System.out.println("复制成功!");
    }

    private static void copy(String f1, String f2) throws IOException {
        File file1=new File(f1);
        /*     File file2=new File(f2);*/

        File[] flist=file1.listFiles();
        for (File f : flist) {
            if(f.isFile()){

                copyFile2(f.getPath(), f2 + "/" + f.getName()); //调用复制文件的方法
                System.out.println("原路径[" + f.getPath() + "] 被复制路径[" + f2 + "/" + f.getName() + "]");

            }else if(f.isDirectory()){
                copyFile1(f.getPath(),f2+"/"+f.getName()); //调用复制文件夹的方法
                System.out.println("原路径["+f.getPath()+"] 被复制路径["+f2+"/"+f.getName()+"]");
            }
        }

    }

    /**
     * 复制文件夹
     * @throws IOException
     */
    public static void copyFile1(String f1,String f2) throws IOException{
        //创建文件夹
        File file=new File(f2);
        if(!file.exists()){
            file.mkdirs();
        }
        copy(f1,f2);
    }

    /**
     * 复制文件
     * @throws IOException
     */
    public static void copyFile2(String f1, String f2) throws IOException {
        //只复制指定的文件后缀名文件
        if (f1.endsWith(".java")) {
            try {
                InputStream input = new FileInputStream(f1);
                //调用EncodingDetect的getCharset方法获取文件的编码格式
                String inputFileEncode = EncodingDetect.getCharset(f1);
                //传入获取到的inputFileEncode编码格式，然后进行转换
                InputStreamReader isr = new InputStreamReader(input, inputFileEncode);
                OutputStream output = new FileOutputStream(f2);
                OutputStreamWriter isw = new OutputStreamWriter(output, "UTF-8");
//            byte[] bt=new byte[1024];
                int read = -1;
                if ((isr != null) && (isw != null)) {


                    while ((read = isr.read()) != (-1)) {
                        isw.write(read);
                        isw.flush();
                    }
                }

                if (isr != null) {
                    isr.close();
                }
                if (isw != null) {
                    isw.close();
                }

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }
}


